package com.songlanyun.modules.pointsexchangeconfig.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.songlanyun.common.exception.RRException;
import com.songlanyun.modules.exception.ConfigException;
import com.songlanyun.modules.pointsexchangeconfig.dao.PointsExchangeConfigDao;
import com.songlanyun.modules.pointsexchangeconfig.entity.PointsExchangeConfigEntity;
import com.songlanyun.modules.pointsexchangeconfig.service.PointsExchangeConfigService;
import org.springframework.stereotype.Service;

import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.songlanyun.common.utils.PageUtils;
import com.songlanyun.common.utils.Query;
import sun.misc.REException;


@Service("pointsExchangeConfigService")
public class PointsExchangeConfigServiceImpl extends ServiceImpl<PointsExchangeConfigDao, PointsExchangeConfigEntity> implements PointsExchangeConfigService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PointsExchangeConfigEntity> page = this.page(
                new Query<PointsExchangeConfigEntity>().getPage(params),
                new QueryWrapper<PointsExchangeConfigEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void add(PointsExchangeConfigEntity pointsExchangeConfig) {
        PointsExchangeConfigEntity config = this.loadConfig(false);
        if (ObjectUtil.isNotNull(config)) {
            pointsExchangeConfig.setId(config.getId());
        }
        this.saveOrUpdate(pointsExchangeConfig);
    }

    @Override
    public PointsExchangeConfigEntity loadConfig(boolean tw) {
        PointsExchangeConfigEntity config = this.lambdaQuery().last("limit 1").one();
        if (ObjectUtil.isNull(config) && tw) {
            throw new RRException(ConfigException.THE_POINTS_EXCHANGE_CONFIGURATION_DOES_NOT_EXIST);
        }

        return config;
    }

}
